



<!DOCTYPE html>
<html lang="zh-CN">
  <head><meta name="generator" content="Hexo 3.9.0">
    <title>客户端存储 — Vue.js</title>
    <meta charset="utf-8">
    <meta name="description" content="Vue.js - The Progressive JavaScript Framework">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="alternate" hreflang="x-default" href="https://vuejs.org/v2/cookbook/client-side-storage.html">
    <link rel="alternate" hreflang="zh" href="https://cn.vuejs.org/v2/cookbook/client-side-storage.html">
    <link rel="alternate" hreflang="ja" href="https://jp.vuejs.org/v2/cookbook/client-side-storage.html">
    <link rel="alternate" hreflang="ru" href="https://ru.vuejs.org/v2/cookbook/client-side-storage.html">
    <link rel="alternate" hreflang="ko" href="https://kr.vuejs.org/v2/cookbook/client-side-storage.html">
    <link rel="alternate" hreflang="pt-BR" href="https://br.vuejs.org/v2/cookbook/client-side-storage.html">
    <link rel="alternate" hreflang="fr" href="https://fr.vuejs.org/v2/cookbook/client-side-storage.html">
    <link rel="alternate" hreflang="es" href="https://es.vuejs.org/v2/cookbook/client-side-storage.html">

    <meta property="og:type" content="article">
    <meta property="og:title" content="客户端存储 — Vue.js">
    <meta property="og:description" content="Vue.js - The Progressive JavaScript Framework">
    <meta property="og:image" content="https://cn.vuejs.org/images/logo.png">

    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="客户端存储 — Vue.js">
    <meta name="twitter:description" content="Vue.js - The Progressive JavaScript Framework">
    <meta name="twitter:image" content="https://cn.vuejs.org/images/logo.png">

    <link rel="apple-touch-icon" sizes="57x57" href="/vue2/images/icons/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/vue2/images/icons/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/vue2/images/icons/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/vue2/images/icons/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/vue2/images/icons/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/vue2/images/icons/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/vue2/images/icons/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/vue2/images/icons/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/vue2/images/icons/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192" href="/vue2/images/icons/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/vue2/images/icons/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="/vue2/images/icons/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/vue2/images/icons/favicon-16x16.png">
    <meta name="msapplication-TileImage" content="/images/icons/ms-icon-144x144.png">
    <link rel="icon" href="/vue2/images/logo.svg">

    <meta name="msapplication-TileColor" content="#4fc08d">
    <meta name="theme-color" content="#4fc08d">

    <meta name="msapplication-config" content="browserconfig.xml">
    <link rel="manifest" href="/vue2/manifest.json">

    <!-- <link href="https://fonts.gstatic.com" rel="preconnect" crossorigin> -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com" rel="preconnect" crossorigin> -->

    <!-- <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600|Roboto Mono&display=swap" rel="stylesheet"> -->
    <!-- <link href="https://fonts.googleapis.com/css?family=Dosis:500&text=Vue.js&display=swap" rel="stylesheet"> -->

    <link href="//code.bdstatic.com/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- main page styles -->
    <link rel="stylesheet" href="/vue2/css/page.css">

    <!-- this needs to be loaded before guide's inline scripts -->
    <script src="/vue2/js/vue.js"></script>

    

    <script>
      Vue.config.productionTip = false
      window.PAGE_TYPE = "cookbook"
    </script>

    <!-- ga -->
    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

      ga('create', 'UA-46852172-3', 'cn.vuejs.org');
      ga('send', 'pageview');
    </script>

    <!-- vimeo analytics -->
    <!-- <script type="text/javascript" defer="defer" src="https://extend.vimeocdn.com/ga/72160148.js"></script> -->
</head>
  <body class="docs">

    

    <div id="mobile-bar">
      <a class="menu-button"></a>
      <a class="logo" href="/"></a>
    </div>
    <div>
  <div id="v3-banner">
    <span class="hidden-sm">非官方文档，仅为个人学习使用，查看官方文档请移步</span><a href="https://cn.vuejs.org/" target="_blank">这里</a>。
  </div>

  <header id="header">
    <a id="logo" href="/vue2/">
      <img src="/vue2/images/logo.svg" alt="vue logo">
      <span>Vue.js</span>
    </a>
    <ul id="nav">
      <li>
  <form id="search-form">
    <input type="text" id="search-query-nav" class="search-query st-default-search-input" aria-label="搜索">
  </form>
</li>
<li class="nav-dropdown-container learn">
  <a class="nav-link current">学习</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><h4>文档</h4></li>
    <li>
      <ul>
        <li><a href="/vue2/v2/guide/" class="nav-link">教程</a></li>
        <li><a href="/vue2/v2/api/" class="nav-link">API</a></li>
        <li><a href="/vue2/v2/style-guide/" class="nav-link">风格指南</a></li>
        <li><a href="/vue2/v2/examples/" class="nav-link">示例</a></li>
        <li><a href="/vue2/v2/cookbook/" class="nav-link current">Cookbook</a></li>
      </ul>
    </li>
    <li><h4>视频教程</h4></li>
    <li>
      <ul>
        <li>
          <a href="https://www.vuemastery.com/courses/" class="nav-link" target="_blank" rel="sponsored noopener">
            Vue Mastery (英文)
          </a>
        </li>
        <li>
          <a href="https://vueschool.io/?friend=vuejs&utm_source=Vuejs.org&utm_medium=Link&utm_content=Navbar%20Dropdown" class="nav-link" target="_blank" rel="sponsored noopener">
            Vue School (英文)
          </a>
        </li>
        <!-- start: special logic for cn -->
        <li>
          <a href="https://learning.dcloud.io/" class="nav-link" target="_blank" rel="sponsored noopener">
            DCloud 视频教程
          </a>
        </li>
        <!-- end: special logic for cn -->
      </ul>
    </li>
  </ul>
</li>

<li class="nav-dropdown-container ecosystem">
  <a class="nav-link">生态系统</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><h4>帮助</h4></li>
    <li><ul>
      <li><a href="https://forum.vuejs.org/" class="nav-link" target="_blank" rel="noopener">论坛</a></li>
      <li><a href="https://chat.vuejs.org/" class="nav-link" target="_blank" rel="noopener">聊天室</a></li>
      <li><a href="https://events.vuejs.org/meetups/" class="nav-link" target="_blank" rel="noopener">聚会</a></li>
    </ul></li>
    <li><h4>工具</h4></li>
    <li>
      <ul>
        <li><a href="https://github.com/vuejs/vue-devtools" class="nav-link" target="_blank" rel="noopener">Devtools</a></li>
        <li><a href="https://cli.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue CLI</a></li>
        <li><a href="https://vue-loader.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue Loader</a></li>
      </ul>
    </li>
    <li><h4>核心插件</h4></li>
    <li><ul>
      <li><a href="https://router.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue Router</a></li>
      <li><a href="https://vuex.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vuex</a></li>
      <li><a href="https://ssr.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue 服务端渲染</a></li>
    </ul></li>
    <li><h4>信息</h4></li>
    <li><ul>
      <li><a href="https://news.vuejs.org" class="nav-link" target="_blank" rel="noopener">周刊</a></li>
      <li><a href="https://github.com/vuejs/vue/projects/6" class="nav-link" target="_blank" rel="noopener">Roadmap</a></li>
      <li><a href="https://events.vuejs.org/" class="nav-link" target="_blank" rel="noopener">活动</a></li>
      <li><a href="https://twitter.com/vuejs" class="nav-link" target="_blank" rel="noopener">Twitter</a></li>
      <li><a href="https://medium.com/the-vue-point" class="nav-link" target="_blank" rel="noopener">博客</a></li>
      <li><a href="https://vuejobs.com/?ref=vuejs" class="nav-link" target="_blank" rel="noopener">工作</a></li>
      <li><a href="https://dev.to/t/vue" class="nav-link" target="_blank" rel="noopener">DEV 社区</a></li>
    </ul></li>
  </ul>
</li>

<li>
  <a href="/vue2/v2/guide/team.html" class="nav-link team">团队</a>
</li>
<li class="nav-dropdown-container resources">
  <a href="#" class="nav-link">资源列表</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="/vue2/resources/partners.html" class="nav-link">合作伙伴</a></li>
    <li><a href="/vue2/resources/themes.html" class="nav-link">主题</a></li>
    <li><a href="https://github.com/vuejs/awesome-vue" class="nav-link" target="_blank" rel="noopener">Awesome Vue</a></li>
    <li><a href="https://awesomejs.dev/for/vue/" class="nav-link" target="_blank" rel="noopener">浏览和 Vue 相关的包</a></li>
  </ul>
</li>

<!-- <li>
  <a href="/vue2/partners" class="nav-link ">Partners</a>
</li> -->
<li class="nav-dropdown-container support-vue">
  <a href="/support-vuejs/" class="nav-link">支持 Vue</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="/support-vuejs/#One-time-Donations" class="nav-link">一次性赞助</a></li>
    <li><a href="/support-vuejs/#Recurring-Pledges" class="nav-link">周期性赞助</a></li>
    <!-- start: special logic for cn -->
    <li><a href="https://www.smallsticker.com/%E8%B4%B4%E7%BA%B8/vue.html" rel="noopener" class="nav-link">贴纸</a></li>
    <li><a href="https://osholic.com/?utm_source=vue&utm_medium=dropdown" rel="noopener" class="nav-link">周边</a></li>
    <!-- end: special logic for cn -->
    <li><a href="https://vue.threadless.com" target="_blank" rel="noopener" class="nav-link">T 恤商店</a></li>
  </ul>
</li>

<li class="nav-dropdown-container language">
  <a class="nav-link">多语言</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="https://vuejs.org/v2/cookbook/client-side-storage.html" class="nav-link">English</a></li>
    <li><a href="https://jp.vuejs.org/v2/cookbook/client-side-storage.html" class="nav-link">日本語</a></li>
    <li><a href="https://ru.vuejs.org/v2/cookbook/client-side-storage.html" class="nav-link">Русский</a></li>
    <li><a href="https://kr.vuejs.org/v2/cookbook/client-side-storage.html" class="nav-link">한국어</a></li>
    <li><a href="https://br.vuejs.org/v2/cookbook/client-side-storage.html" class="nav-link">Português</a></li>
    <li><a href="https://fr.vuejs.org/v2/cookbook/client-side-storage.html" class="nav-link">Français</a></li>
    <li><a href="https://vi.vuejs.org/v2/cookbook/client-side-storage.html" class="nav-link">Tiếng Việt</a></li>
    <li><a href="https://es.vuejs.org/v2/cookbook/client-side-storage.html" class="nav-link">Español</a></li>
    <li><a href="https://docs.vuejs.id/v2/cookbook/client-side-storage.html" class="nav-link">Bahasa Indonesia</a></li>
  </ul>
</li>

<!-- start: special logic for cn -->
<li><a href="https://github.com/vuejs/cn.vuejs.org/" target="_blank" class="nav-link contribute">参与翻译</a></li>
<!-- end: special logic for cn -->

    </ul>
  </header>
</div>

    
      <div id="main" class="fix-sidebar">
        
  

<div class="sidebar">
  <div class="sidebar-inner">
    
    <div class="list">
      <div id="sidebar-sponsors-special">
  <div class="main-sponsor">
    <!-- start: special logic for cn -->
    <span>特别赞助商</span>
    <div>
    <a href="http://www.dcloud.io/?hmsr=vuejsorg&hmpl=&hmcu=&hmkw=&hmci=" target="_blank" rel="sponsored noopener" class="logo">
      <img id="s-dcloud" alt="dcloud">
      <script>
      (function(){
        var el = document.getElementById("s-dcloud");
        var adImg = null;
        var altImg = "/vue2/images/dcloud2.png";
        var img = "/vue2/images/dcloud1.png";
        el.src = adImg || (altImg && Math.random() >= 0.5 ? altImg : img);
      })()
      </script>
    </a>
    </div>
    <div>
    <a href="https://authing.cn/welcome?from=vuejs" target="_blank" rel="sponsored noopener" class="logo">
      <img id="s-authing" alt="authing">
      <script>
      (function(){
        var el = document.getElementById("s-authing");
        var adImg = null;
        var altImg = null;
        var img = "/vue2/images/authing.svg";
        el.src = adImg || (altImg && Math.random() >= 0.5 ? altImg : img);
      })()
      </script>
    </a>
    </div>
    <div>
    <a href="https://qingfuwu.cn?utm_campaign=TR_eSJH7nqW&utm_content=&utm_medium=Web&utm_source=CH_53OxwryD&utm_term=" target="_blank" rel="sponsored noopener" class="logo">
      <img id="s-qingfuwu" alt="qingfuwu">
      <script>
      (function(){
        var el = document.getElementById("s-qingfuwu");
        var adImg = null;
        var altImg = null;
        var img = "/vue2/images/qingfuwu.svg";
        el.src = adImg || (altImg && Math.random() >= 0.5 ? altImg : img);
      })()
      </script>
    </a>
    </div>
    <!-- end: special logic for cn -->
  </div>
</div>
<!--
<div id="sidebar-sponsors-platinum-left">
  <div class="main-sponsor">
    <span>白金赞助商</span>
    <div>
    <a href="https://vueschool.io/?utm_source=Vuejs.org&utm_medium=Banner&utm_campaign=Sponsored%20Banner&utm_content=V1" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/vueschool.png" alt="VueSchool">
    </a>
    <a href="https://vehikl.com/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/vehikl.png" alt="Vehikl">
    </a>
    <a href="https://retool.com/?utm_source=sponsor&utm_campaign=vue" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/retool.png" alt="Retool">
    </a>
    <a href="https://passionatepeople.io/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/passionate_people.png" alt="Passionate People">
    </a>
    <a href="https://www.storyblok.com" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/storyblok.png" alt="Storyblok">
    </a>
    <a href="https://ionicframework.com/vue?utm_source=partner&utm_medium=referral&utm_campaign=vuesponsorship&utm_content=vuedocs" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/ionic.png" alt="Ionic">
    </a>
    <a href="https://nuxtjs.org/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/nuxt.png" alt="Nuxt">
    </a>
    </div>
  </div>
  <a class="become-backer" href="/vue2/support-vuejs">
    成为赞助者
  </a>
</div>

-->

      
        <h2>
          
          Cookbook<sup class="beta">beta</sup>
          
        </h2>
        <ul class="menu-root">
  
    
    
    <li>
      <a href="/vue2/v2/cookbook/index.html" class="sidebar-link">介绍</a>
    </li>
  
    
    
    <li>
      <a href="/vue2/v2/cookbook/adding-instance-properties.html" class="sidebar-link">添加实例 property</a>
    </li>
  
    
    
    <li>
      <a href="/vue2/v2/cookbook/form-validation.html" class="sidebar-link">表单校验</a>
    </li>
  
    
    
    <li>
      <a href="/vue2/v2/cookbook/editable-svg-icons.html" class="sidebar-link">可编辑的 SVG 图标系统</a>
    </li>
  
    
    
    <li>
      <a href="/vue2/v2/cookbook/serverless-blog.html" class="sidebar-link">创建一个基于 CMS 的博客</a>
    </li>
  
    
    
    <li>
      <a href="/vue2/v2/cookbook/unit-testing-vue-components.html" class="sidebar-link">Vue 组件的单元测试</a>
    </li>
  
    
    
    <li>
      <a href="/vue2/v2/cookbook/creating-custom-scroll-directives.html" class="sidebar-link">创建自定义滚动指令</a>
    </li>
  
    
    
    <li>
      <a href="/vue2/v2/cookbook/debugging-in-vscode.html" class="sidebar-link">在 VS Code 中调试</a>
    </li>
  
    
    
    <li>
      <a href="/vue2/v2/cookbook/using-axios-to-consume-apis.html" class="sidebar-link">使用 axios 访问 API</a>
    </li>
  
    
    
    <li>
      <a href="/vue2/v2/cookbook/avoiding-memory-leaks.html" class="sidebar-link">避免内存泄漏</a>
    </li>
  
    
    
    <li>
      <a href="/vue2/v2/cookbook/client-side-storage.html" class="sidebar-link current">客户端存储</a>
    </li>
  
    
    
    <li>
      <a href="/vue2/v2/cookbook/packaging-sfc-for-npm.html" class="sidebar-link">Packaging Vue Components for npm</a>
    </li>
  
    
    
    <li>
      <a href="/vue2/v2/cookbook/dockerize-vuejs-app.html" class="sidebar-link">Dockerize Vue.js App</a>
    </li>
  
    
    
    <li>
      <a href="/vue2/v2/cookbook/practical-use-of-scoped-slots.html" class="sidebar-link">Practical use of scoped slots with GoogleMaps</a>
    </li>
  
</ul>

      
    </div>
  </div>
</div>
<!--

<div id="sidebar-sponsors-platinum-right">
  <div class="main-sponsor">
    <span>白金赞助商</span>
    <div>
    <a href="https://vueschool.io/?utm_source=Vuejs.org&utm_medium=Banner&utm_campaign=Sponsored%20Banner&utm_content=V1" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/vueschool.png" alt="VueSchool">
    </a>
    <a href="https://vehikl.com/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/vehikl.png" alt="Vehikl">
    </a>
    <a href="https://retool.com/?utm_source=sponsor&utm_campaign=vue" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/retool.png" alt="Retool">
    </a>
    <a href="https://passionatepeople.io/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/passionate_people.png" alt="Passionate People">
    </a>
    <a href="https://www.storyblok.com" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/storyblok.png" alt="Storyblok">
    </a>
    <a href="https://ionicframework.com/vue?utm_source=partner&utm_medium=referral&utm_campaign=vuesponsorship&utm_content=vuedocs" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/ionic.png" alt="Ionic">
    </a>
    <a href="https://nuxtjs.org/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/nuxt.png" alt="Nuxt">
    </a>
    </div>
  </div>
  <a class="become-backer" href="/vue2/support-vuejs">
    成为赞助者
  </a>
</div>


-->


<div class="content cookbook with-sidebar ">
  <p class="tip warning v3-warning">
    您在浏览的是 v2.x 及更早版本的文档。v3.x 的文档<a href="https://wangyubina.github.io/vue3/">在这里</a>。
  </p>

  
    
      
<div id="ad">
  <!-- start: special logic for cn -->
  <div class="wwads-cn wwads-vertical" data-id="53" style="max-width: 200px"></div>
  <script type="text/javascript" src="https://cdn.wwads.cn/js/makemoney.js" async></script>
  <!-- end: special logic for cn -->
  <!-- <script
    async
    type="text/javascript"
    src="//cdn.carbonads.com/carbon.js?serve=CEBDT27Y&placement=vuejsorg"
    id="_carbonads_js"
  ></script> -->
</div>


    
  
  
    <h1>客户端存储</h1>
  

  <!-- start: special logic for cn -->
  <!-- start: special logic for cn -->
<!-- <div class="ad-pagetop">
  <a href="http://www.vueshop.com.cn/index.php?http_referer=vuejs" target="_blank" rel="noopener noreferrer">
    <span class="name">VUEshop</span>
    <span class="description">中国免费商城系统 - 搜豹商城系统 - 免费50小时 Vue 视频教程</span>
    <span class="action">立即查看 &gt;</span>
  </a>
</div> -->
<!-- end: special logic for cn -->

  <!-- end: special logic for cn -->

  
    <h2 id="基本的示例"><a href="#基本的示例" class="headerlink" title="基本的示例"></a>基本的示例</h2><p>客户端存储是快速为一个应用进行性能优化的绝佳方法。通过把数据存储在浏览器中，用户不必每次都向服务器请求获取同一个信息。在你离线时，使用本地存储的数据而不是向远端服务器上请求数据就显得非常有用，甚至在线用户也可以从中获益。客户端存储可以通过这些技术来实现：<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies" target="_blank" rel="noopener">cookie</a>、<a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API" target="_blank" rel="noopener">Local Storage</a> (更准确地说是“Web Storage”)、<a href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API" target="_blank" rel="noopener">IndexedDB</a> 和 <a href="https://www.w3.org/TR/webdatabase/" target="_blank" rel="noopener">WebSQL</a> (这项技术已经被废弃了，你不应该在新项目中使用它)。</p>
<p>在这个 cookbook 的条目中，我们将专注于最简单的存储机制：Local Storage。Local Storage 使用键/值对来存储数据。它仅支持存储简单的值，但也可以通过 JSON 编解码来存储复杂的数据。总的来说，Local Storage 适合存储你希望进行持久化的较小数据集，比如用户偏好设置或表单数据。更大规模和更复杂的数据则适合存储在 IndexedDB 中。</p>
<p>让我们从一个表单的简单示例开始：</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"app"</span>&gt;</span>
  My name is <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">v-model</span>=<span class="hljs-string">"name"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre>
<p>这个示例中的表单字段绑定了一个叫 <code>name</code> 的值。下面是 JavaScript 代码：</p>
<pre><code class="hljs js"><span class="hljs-keyword">const</span> app = <span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">el</span>: <span class="hljs-string">'#app'</span>,
  <span class="hljs-attr">data</span>: &#123;
    <span class="hljs-attr">name</span>: <span class="hljs-string">''</span>
  &#125;,
  mounted() &#123;
    <span class="hljs-keyword">if</span> (localStorage.name) &#123;
      <span class="hljs-keyword">this</span>.name = localStorage.name;
    &#125;
  &#125;,
  <span class="hljs-attr">watch</span>: &#123;
    name(newName) &#123;
      localStorage.name = newName;
    &#125;
  &#125;
&#125;);</code></pre>
<p>请注意 <code>mounted</code> 和 <code>watch</code> 两个方法。我们使用 <code>mounted</code> 方法来从 <code>localStorage</code> 中加载数据。为了将数据写入，我们侦听 <code>name</code> 值的变化，并将数据实时写入。</p>
<p>你可以在下面运行这个程序：</p>
<p data-height="265" data-theme-id="0" data-slug-hash="KodaKb" data-default-tab="js,result" data-user="cfjedimaster" data-embed-version="2" data-pen-title="testing localstorage" class="codepen">See the Pen <a href="https://codepen.io/cfjedimaster/pen/KodaKb/" target="_blank" rel="noopener">testing localstorage</a> by Raymond Camden (<a href="https://codepen.io/cfjedimaster" target="_blank" rel="noopener">@cfjedimaster</a>) on <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a>.</p><br><script async src="https://static.codepen.io/assets/embed/ei.js"></script><br><br>在表单中输入一些东西，然后刷新页面。你会发现之前输入的值自动出现了。别忘了你的浏览器提供了好用的开发者工具来检查客户端存储的情况。这是一个使用 Firefox 的示例：<br><br><img src="/vue2/images/devtools-storage.png" alt="Firefox 中的 Storage 开发工具"><br><br>这是一个使用 Chrome 的示例：<br><br><img src="/vue2/images/devtools-storage-chrome.png" alt="Chrome 中的 Storage 开发工具"><br><br>最后，这是一个使用 Microsoft Edge 的示例。请注意，你可以在 Debugger tab 下找到应用存储的值。<br><br><img src="/vue2/images/devtools-storage-edge.png" alt="Edge 中的 Storage 开发工具"><br><br><p class="tip">除此之外，这些开发工具也可以用来移除存储的数据，在测试时会很有用。</p>

<p>将变化的值立即写入或许是不被推荐的。让我们来考虑一个略微进阶的示例，首先是升级后的表单。</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"app"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
    My name is <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">v-model</span>=<span class="hljs-string">"name"</span>&gt;</span>
    and I am <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">v-model</span>=<span class="hljs-string">"age"</span>&gt;</span> years old.
  <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> @<span class="hljs-attr">click</span>=<span class="hljs-string">"persist"</span>&gt;</span>Save<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre>
<p>现在我们有了两个字段 (依然是绑定到一个 Vue 实例上)，但是多了一个可以运行 <code>persist</code> 方法的按钮。让我们来看 JavaScript 代码。</p>
<pre><code class="hljs js"><span class="hljs-keyword">const</span> app = <span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">el</span>: <span class="hljs-string">'#app'</span>,
  <span class="hljs-attr">data</span>: &#123;
    <span class="hljs-attr">name</span>: <span class="hljs-string">''</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">0</span>
  &#125;,
  mounted() &#123;
    <span class="hljs-keyword">if</span> (localStorage.name) &#123;
      <span class="hljs-keyword">this</span>.name = localStorage.name;
    &#125;
    <span class="hljs-keyword">if</span> (localStorage.age) &#123;
      <span class="hljs-keyword">this</span>.age = localStorage.age;
    &#125;
  &#125;,
  <span class="hljs-attr">methods</span>: &#123;
    persist() &#123;
      localStorage.name = <span class="hljs-keyword">this</span>.name;
      localStorage.age = <span class="hljs-keyword">this</span>.age;
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'now pretend I did more stuff...'</span>);
    &#125;
  &#125;
&#125;)</code></pre>
<p>像之前一样，<code>mounted</code> 方法是用来加载持久化了的数据 (如果存在的话)。这一次，数据只会在点击按钮后才被持久化。我们也可以在数据被存储之前，对数据进行验证或转换。你也可以将日期一并存储进去来记录这些数据是何时被存储的。有了这些元数据，<code>mounted</code> 方法就可以通过逻辑判断来决定是否再次对数据进行存储。你可以在下面对这个版本进行尝试。</p>
<p></p><p data-height="265" data-theme-id="0" data-slug-hash="rdOjLN" data-default-tab="js,result" data-user="cfjedimaster" data-embed-version="2" data-pen-title="testing localstorage 2" class="codepen">See the Pen <a href="https://codepen.io/cfjedimaster/pen/rdOjLN/" target="_blank" rel="noopener">testing localstorage 2</a> by Raymond Camden (<a href="https://codepen.io/cfjedimaster" target="_blank" rel="noopener">@cfjedimaster</a>) on <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a>.</p><p></p>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>

<h2 id="处理复杂的数据"><a href="#处理复杂的数据" class="headerlink" title="处理复杂的数据"></a>处理复杂的数据</h2><p>就像在前文中提到的那样，Local Storage 只适合用于存储简单的值。为了存储对象和数组这样更复杂的数据，你必须使用 JSON 来对数据进行序列化和反序列化。下面这个示例演示了对一个猫的数组进行持久化的操作 (这个数组类型不能更好了)。</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"app"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Cats<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">v-for</span>=<span class="hljs-string">"(cat, n) in cats"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"cat"</span>&gt;</span>&#123;&#123; cat &#125;&#125;<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> @<span class="hljs-attr">click</span>=<span class="hljs-string">"removeCat(n)"</span>&gt;</span>Remove<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">v-model</span>=<span class="hljs-string">"newCat"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> @<span class="hljs-attr">click</span>=<span class="hljs-string">"addCat"</span>&gt;</span>Add Cat<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre>
<p>这个“app”的顶部有一个简单的列表 (还有一个可以移除一只猫的按钮)，底部有一个添加一只新猫的表单。现在我们来看 JavaScript 代码。</p>
<pre><code class="hljs js"><span class="hljs-keyword">const</span> app = <span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">el</span>: <span class="hljs-string">'#app'</span>,
  <span class="hljs-attr">data</span>: &#123;
    <span class="hljs-attr">cats</span>: [],
    <span class="hljs-attr">newCat</span>: <span class="hljs-literal">null</span>
  &#125;,
  mounted() &#123;
    <span class="hljs-keyword">if</span> (localStorage.getItem(<span class="hljs-string">'cats'</span>)) &#123;
      <span class="hljs-keyword">try</span> &#123;
        <span class="hljs-keyword">this</span>.cats = <span class="hljs-built_in">JSON</span>.parse(localStorage.getItem(<span class="hljs-string">'cats'</span>));
      &#125; <span class="hljs-keyword">catch</span>(e) &#123;
        localStorage.removeItem(<span class="hljs-string">'cats'</span>);
      &#125;
    &#125;
  &#125;,
  <span class="hljs-attr">methods</span>: &#123;
    addCat() &#123;
      <span class="hljs-comment">// 确保他们输入了一些东西</span>
      <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">this</span>.newCat) &#123;
        <span class="hljs-keyword">return</span>;
      &#125;

      <span class="hljs-keyword">this</span>.cats.push(<span class="hljs-keyword">this</span>.newCat);
      <span class="hljs-keyword">this</span>.newCat = <span class="hljs-string">''</span>;
      <span class="hljs-keyword">this</span>.saveCats();
    &#125;,
    removeCat(x) &#123;
      <span class="hljs-keyword">this</span>.cats.splice(x, <span class="hljs-number">1</span>);
      <span class="hljs-keyword">this</span>.saveCats();
    &#125;,
    saveCats() &#123;
      <span class="hljs-keyword">const</span> parsed = <span class="hljs-built_in">JSON</span>.stringify(<span class="hljs-keyword">this</span>.cats);
      localStorage.setItem(<span class="hljs-string">'cats'</span>, parsed);
    &#125;
  &#125;
&#125;)</code></pre>
<p>在这个应用中，我们转而调用 Local Storage API 而不再“直接”访问 Local Storage。这两种方法都是有效的，但是调用 API 往往是更值得推荐的方法。<code>mounted</code> 方法现在需要先获取数据，然后对 JSON 格式的数据进行解析。如果这里出现了任何错误，我们就认为数据已经损坏了并将它删除。(请记住，如果你的网页应用使用了客户端存储技术，用户可以随意访问并修改这些存储的数据。)</p>
<p>我们现在有三种方法可以对猫进行操作。<code>addCat</code> 和 <code>removeCat</code> 方法负责更新储存在 <code>this.cats</code> 中的“实时”Vue 数据。在此之后，它们通过 <code>saveCats</code> 方法来序列化和持久化这些数据。你可以在下面体验一下这个版本：</p>
<p></p><p data-height="265" data-theme-id="0" data-slug-hash="qoYbyW" data-default-tab="js,result" data-user="cfjedimaster" data-embed-version="2" data-pen-title="localstorage, complex" class="codepen">See the Pen <a href="https://codepen.io/cfjedimaster/pen/qoYbyW/" target="_blank" rel="noopener">localstorage, complex</a> by Raymond Camden (<a href="https://codepen.io/cfjedimaster" target="_blank" rel="noopener">@cfjedimaster</a>) on <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a>.</p><p></p>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>

<h2 id="替代方案"><a href="#替代方案" class="headerlink" title="替代方案"></a>替代方案</h2><p>尽管 Local Storage API 较为简单，但它缺少了一些在很多应用中都很有用的基本特性。下面几个插件包装了对 Local Storage 的访问并让它变得简单易用，同时加入了诸如默认值等功能。</p>
<ul>
<li><a href="https://github.com/pinguinjkeke/vue-local-storage" target="_blank" rel="noopener">vue-local-storage</a></li>
<li><a href="https://github.com/ropbla9/vue-reactive-storage" target="_blank" rel="noopener">vue-reactive-storage</a></li>
<li><a href="https://github.com/yarkovaleksei/vue2-storage" target="_blank" rel="noopener">vue2-storage</a></li>
</ul>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>虽然浏览器永远不会取代服务器的持久化系统，但是通过多种方法在本地缓存数据可以让你的应用的性能得到大幅度的提升，而与 Vue.js 相结合则会让它更为强大。</p>

  
  
  <div class="footer">
      <script src="//m.servedby-buysellads.com/monetization.js" type="text/javascript"></script>
<div id="bsa-native"></div>
<script>
_bsa.init('custom', 'CKYD62QM', 'placement:vuejsorg',
  {
    target: '#bsa-native',
    template: '<a class="native-box" href="##statlink##"><div class="native-sponsor">Sponsor</div><div class="native-text"><strong>##company##</strong> — ##description##</div></a>'
  }
);
</script>


    发现错误？想参与编辑？
    <a href="https://github.com/vuejs/cn.vuejs.org/blob/master/src/v2/cookbook/client-side-storage.md" rel="noopener" target="_blank">
      在 GitHub 上编辑此页！
    </a>
    <!-- Deployed on
    <a href="https://url.netlify.com/HJ8X2mxP8" rel="noopener" target="_blank">
      Netlify
    </a>. -->
  </div>
</div>

      </div>
      <script src="/vue2/js/smooth-scroll.min.js"></script>
    

    <!-- main custom script for sidebars, version selects etc. -->
    <script src="/vue2/js/css.escape.js"></script>
    <script src="/vue2/js/common.js"></script>

    <!-- search -->
    <link href="//code.bdstatic.com/npm/docsearch.js@1.5.0/dist/cdn/docsearch.min.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="/vue2/css/search.css">
    <script src="//code.bdstatic.com/npm/docsearch.js@1.5.0/dist/cdn/docsearch.min.js"></script>
    <script>
    [
      '#search-query-nav',
      '#search-query-sidebar',
      '#search-query-menu'
    ].forEach(function (selector) {
      if (!document.querySelector(selector)) return
      // search index defaults to v2
      var match = window.location.pathname.match(/^\/(v\d+)/)
      var version = match ? match[1] : 'v2'
      docsearch({
      appId: 'BH4D9OD16A',
      apiKey: '5638280abff9d207417bb03be05f0b25',
      indexName: 'vuejs_cn2',
      inputSelector: selector,
      algoliaOptions: { facetFilters: ["version:" + version] },
      autocompleteOptions: { hint: false, appendTo: 'body'}
      })
    })
    </script>
  </body>
</html>
